//
//  myAccountViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 22-05-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "myAccountViewController.h"
#import "dao.h"
#import "Flurry.h"

@interface myAccountViewController ()

@end

@implementation myAccountViewController

@synthesize textEmail, textActualPassword, textPassword, textRetypePassword, textNames, textLastName, textRut, textNumber, textDay, textMonth, textYear, btnActualizar;
@synthesize viewUpdating, objActivityUpdating, objBtnUpdateCancel;
@synthesize json;
@synthesize segmentedSexOption;

static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 180;

bool blnNumerActiveAccount = NO;
bool upKeyboard = NO;

NSTimer *timerUpdatingAccount;

-(void) hideKeyboard{
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

- (void) upKeyboardClasic{
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

- (void) upKeyboardNumber{
    
    blnNumerActiveAccount = YES;
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

-(void) touchesBegan :(NSSet *) touches withEvent:(UIEvent *)event
{
    
    if (blnNumerActiveAccount) {
        [self hideKeyboard];
        blnNumerActiveAccount = NO;
    }
    
    [self.view endEditing:YES];
    
    [super touchesBegan:touches withEvent:event ];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == textEmail) {
        
        [textEmail resignFirstResponder];
        [textActualPassword becomeFirstResponder];
        
    }
    else if (textField == textActualPassword) {
        
        [textActualPassword resignFirstResponder];
        [textPassword becomeFirstResponder];
    }
    else if (textField == textPassword) {

        [textPassword resignFirstResponder];
        [textRetypePassword becomeFirstResponder];
        
    }else if (textField == textRetypePassword) {

        [textRetypePassword resignFirstResponder];

        [self.view endEditing:YES];

//      [textNames becomeFirstResponder];
        
    }else if (textField == textNames) {
        
        [textNames resignFirstResponder];
        [textLastName becomeFirstResponder];
        
    }else if (textField == textLastName) {
        
        [textLastName resignFirstResponder];
        [textRut becomeFirstResponder];
        
    }else if (textField == textRut) {
        
        [textRut resignFirstResponder];
        [textNumber becomeFirstResponder];
        
    }else{
        [self.view endEditing:YES];
    }

    return NO;
}

//---------------------------------------------------------------------

-(void)cancelNumberPad{
    
    blnNumerActiveAccount = NO;
    
    [self hideKeyboard];
    
    [self.view endEditing:YES];
}

- (void)doneWithNumberPad:(id)sender {
    
    blnNumerActiveAccount = NO;
    //Observación: Bajamos el teclado
    
    [self hideKeyboard];
    [self.view endEditing:YES];
}

- (IBAction)changePhoneNumber:(id)sender {

    if (blnNumerActiveAccount) {
        [self hideKeyboard];
//      [self.view endEditing:YES];
        blnNumerActiveAccount = NO;
    }
    
    if (!blnNumerActiveAccount) {
        blnNumerActiveAccount = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textNumber.inputAccessoryView = numberToolbar;
    }
    
}

- (IBAction)changeDay:(id)sender {
    
    if (blnNumerActiveAccount) {
        [self hideKeyboard];
//      [self.view endEditing:YES];
        blnNumerActiveAccount = NO;
    }
    
    if (!blnNumerActiveAccount) {
        
        blnNumerActiveAccount = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textDay.inputAccessoryView = numberToolbar;
    }
}

- (IBAction)changeMonth:(id)sender {

    if (blnNumerActiveAccount) {
        [self hideKeyboard];
//      [self.view endEditing:YES];
        blnNumerActiveAccount = NO;
    }
    
    if (!blnNumerActiveAccount) {
        
        blnNumerActiveAccount = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textMonth.inputAccessoryView = numberToolbar;
    }
}

- (IBAction)changeYear:(id)sender {
    
    if (blnNumerActiveAccount) {
        [self hideKeyboard];
//      [self.view endEditing:YES];
        blnNumerActiveAccount = NO;
    }
    
    if (!blnNumerActiveAccount) {
        
        blnNumerActiveAccount = YES;
        
        [self upKeyboardNumber];
        
        UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
        numberToolbar.barStyle = UIBarStyleDefault;
        
        numberToolbar.items = [NSArray arrayWithObjects:
                               [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                               [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                               [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                               nil];
        
        [numberToolbar sizeToFit];
        
        textYear.inputAccessoryView = numberToolbar;
    }
}

- (IBAction)editAccount:(id)sender {

    if (btnActualizar.hidden == YES) {

        objBtnUpdateCancel.title = @"Cerrar";
        
        [self editValuesItems:YES];
        
        textEmail.text = textEmail.placeholder;

        textActualPassword.text = @"";
        textPassword.text = @"";
        textRetypePassword.text = @"";
        
        textNames.text = textNames.placeholder;
        textLastName.text = textLastName.placeholder;
        textRut.text = textRut.placeholder;
        textNumber.text = textNumber.placeholder;
        textDay.text = textDay.placeholder;
        textMonth.text = textMonth.placeholder;
        textYear.text = textYear.placeholder;
        segmentedSexOption.enabled = YES;
        
        btnActualizar.hidden = NO;

    }else{
        objBtnUpdateCancel.title = @"Editar";
        
        [self editValuesItems:NO];
        
        textEmail.placeholder = textEmail.text;
        textEmail.text = @"";

        textActualPassword.placeholder = textActualPassword.text;
        textActualPassword.text = @"";
        
        textPassword.placeholder = textPassword.text;
        textPassword.text = @"";
        
        textRetypePassword.placeholder = textRetypePassword.text;
        textRetypePassword.text = @"";
        
        textNames.placeholder = textNames.text;
        textNames.text = @"";
        
        textLastName.placeholder = textLastName.text;
        textLastName.text = @"";
        
        textRut.placeholder = textRut.text;
        textRut.text = @"";
        
        textNumber.placeholder = textNumber.text;
        textNumber.text = @"";
        
        textDay.placeholder = textDay.text;
        textDay.text = @"";
        
        textMonth.placeholder = textMonth.text;
        textMonth.text = @"";
        
        textYear.placeholder = textYear.text;
        textYear.text = @"";
        
        segmentedSexOption.enabled = NO;
        
        btnActualizar.hidden = YES;
    }
    
}

-(bool) validarRut: (NSString *) strRut {
    
    int rut = 0;
    int Digito;
    int Contador;
    int Multiplo;
    int Acumulador;
    NSString *dvCalulado;
    
    //-----------------------------------------------------------------------------------------
    strRut = [strRut stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
    strRut = [strRut stringByReplacingOccurrencesOfString: @ "-" withString: @ ""];
    
    int rutAux = [[strRut substringWithRange:NSMakeRange(0, strRut.length-1)] intValue];
    //  char dv = (char) [strRut substringWithRange:NSMakeRange(strRut.length-1, 1 )];
    NSString *dv = [[strRut substringWithRange:NSMakeRange(strRut.length-1, 1 )] uppercaseString];
    
    rut = rutAux;
    //-----------------------------------------------------------------------------------------
    
    Contador = 2;
    Acumulador = 0;
    
    while (rut != 0)
    {
        Multiplo = (rut % 10) * Contador;
        Acumulador = Acumulador + Multiplo;
        rut = rut/10;
        Contador = Contador + 1;
        if (Contador == 8)
        {
            Contador = 2;
        }
    }
    
    Digito = 11 - (Acumulador % 11);
    
    dvCalulado = [NSString stringWithFormat:@"%i", Digito];   //Digito.ToString().Trim();
    
    if (Digito == 10 )
    {
        dvCalulado = @"K";
    }
    if (Digito == 11)
    {
        dvCalulado = @"0";
    }
    
    NSLog(@"dv=%@", dv);
    
    NSLog(@"dvCalulado =%@", dvCalulado);
    
    if ([dvCalulado isEqualToString:dv]) {
        
        return YES;
        
    }else{
        return NO;
    }
    
}

-(bool) validarRegistro{
    
    bool blnRetorno = YES;
    NSString *strMensaje = @"";
    
    //Nombres
    if (textNames.text.length == 0) {
        [textNames becomeFirstResponder];
        strMensaje = @"Debe ingresar el nombre del cliente.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    //Apellidos
    if (textLastName.text.length == 0) {
        [textLastName becomeFirstResponder];
        strMensaje = @"Debe ingresar los apellidos del cliente.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    //RUT
    
    if (textRut.text.length == 0) {
        [textRut becomeFirstResponder];
        strMensaje = @"Debe ingresar el rut del cliente.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    bool blnValidaRut = YES;
    
    textRut.text = [textRut.text uppercaseString];
    
    NSLog(@"textRut.text =%@", textRut.text);
    
    blnValidaRut = [self validarRut:textRut.text];
    
    if (!blnValidaRut) {
        [textRut becomeFirstResponder];
        strMensaje = @"El rut ingresado es incorrecto.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    //Número Celular
    if (textNumber.text.length == 0) {
        [textNumber becomeFirstResponder];
        strMensaje = @"Debe ingresar el número de celular.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    if (textNumber.text.length < 8) {
        [textNumber becomeFirstResponder];
        strMensaje = @"Debe ingresar un número válido de 8 caracteres.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    //Dia
    if (textDay.text.length == 0) {
        [textDay becomeFirstResponder];
        strMensaje = @"Debe ingresar el día de nacimiento.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    //Mes
    if (textMonth.text.length == 0) {
        [textMonth becomeFirstResponder];
        strMensaje = @"Debe ingresar el mes de nacimiento.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    //Ano
    if (textYear.text.length == 0) {
        [textYear becomeFirstResponder];
        strMensaje = @"Debe ingresar el año de nacimiento.";
        blnRetorno = NO;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:strMensaje
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return blnRetorno;
    }
    
    
    return blnRetorno;
}

- (IBAction)updateAccount:(id)sender {
    
    viewUpdating.hidden = NO;
    
    timerUpdatingAccount = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateAccountSelector:) userInfo:nil repeats:YES];
    
}

-(NSString *) transformarCaracteresComposables: (NSString *)string{
    
    NSString *strStringTransformado = @"";
    //  NSString *strStringGeneral = @"";
    int intLargoString = 0;
    
    intLargoString = (int) string.length;
    
    for (int i=0; i < intLargoString; i++) {
        
        unichar c = [string characterAtIndex:i];
        NSLog(@"c=%C", c);
        
        if ([[NSCharacterSet decomposableCharacterSet] characterIsMember:c]) { //Si es con acentos la letra
            
            CFStringRef originalString = (__bridge CFStringRef)([NSString stringWithCharacters:&c length:1]);
            CFStringRef encodedString = CFURLCreateStringByAddingPercentEscapes(
                                                                                kCFAllocatorDefault,
                                                                                originalString,
                                                                                NULL,
                                                                                CFSTR(":/?#[]@!$&'()*+,;="),
                                                                                kCFStringEncodingUTF8);
            
            strStringTransformado = [NSString stringWithFormat:@"%@%@", strStringTransformado, encodedString];
        }else{
            strStringTransformado =  [NSString stringWithFormat:@"%@%@", strStringTransformado, [NSString stringWithCharacters:&c length:1]];
            
        }
    }
    
    NSLog(@"strStringTransformado=%@", strStringTransformado);
    
    return strStringTransformado;
}

//strJsonBase=JsonPassUpd&strIdUsuario=%i&strClaveUsuarioSistema=%@

-(bool)updatePasswordCloud{

    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = 0; //Respuesta del Cloud
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSString *stringReplace = @"";
    
    stringReplace = [self transformarCaracteresComposables:textPassword.text];
    
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL * url = [NSURL URLWithString:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraUsuario.aspx"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
    NSString * params =[NSString stringWithFormat:@"strJsonBase=JsonUsuarioPassUpd&strIdUsuario=%i&strClaveUsuarioSistema=%@",  intIdUsuario, stringReplace];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSNonLossyASCIIStringEncoding]];//NSNonLossyASCIIStringEncoding  NSUTF8StringEncoding
    
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           NSLog(@"Response:%@ %@\n", response, error);
                                                           if(error == nil)
                                                           {
                                                               NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                               NSLog(@"Data = %@",text);
                                                           }
                                                       }];
    [dataTask resume];

    return  YES;

}

-(bool) updateUserSystem{

    dao *objDAO = [[dao alloc] init];
    
    //----------------------------------------------------------------
    //Observación: Llamada remota al Cloud para crear el Id usuario
    //----------------------------------------------------------------
    int intIdUsuario = 0; //Respuesta del Cloud
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    NSString *strUser, *strActualPassword, *strPassword, *strEmail;
    NSString *strActualPasswordStored = [objDAO obtainCurrentPasswordUserSistem:intIdUsuario];
    
    strUser = @"";
    strActualPassword = textActualPassword.text;
    strPassword = textPassword.text;
    strEmail = textEmail.text;

    if (![strActualPasswordStored  isEqual: strActualPassword]) { //Si no son iguales no hago nada
        
        return NO;
        
    }else{

        //Actualizamos en el Cloud
        [self updatePasswordCloud];

        //Actualizamos localmente
        int intRetorno = 0;
        intRetorno = [objDAO updatePasswordUserSistem:intIdUsuario strPassword:strPassword];
        
        if (intRetorno > 0) {
            return YES;
        }else{
            return NO;
        }
        
    }
    
}

-(BOOL) insertClientCloud:(int) intIdUsuario
                 strEmail:(NSString *) strEmail
         intIdTipoCliente:(int) intIdTipoCliente
            intRutCliente:(int) intRutCliente
                strDigito:(NSString *) strDigito
        strNombreCompleto:(NSString *) strNombreCompleto
             strApellidos:(NSString *) strApellidos
           strRazonSocial:(NSString *) strRazonSocial
        strNombreFantasia:(NSString *) strNombreFantasia
              strTelefono:(NSString *) strTelefono
               strCelular:(NSString *) strCelular
       intFechaNacimiento:(int) intFechaNacimiento
                  strSexo:(NSString *) strSexo
               intIdRubro:(int) intIdRubro
         strFlagDireccion:(NSString *) strFlagDireccion {
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCliente.aspx?strJsonBase=JsonRegistraClientes&strIdUsuario=%i&strEmail=%@&strIdTipoCliente=%i&strRutCliente=%i&strDigito=%@&strNombreCompleto=%@&strApellidos=%@&strRazonSocial=%@&strNombreFantasia=%@&strTelefono=%@&strCelular=%@&strFechaNacimiento=%i&strSexo=%@&strIdRubro=%i&strFlagDireccion=%@",
                        intIdUsuario, strEmail, intIdTipoCliente, intRutCliente, strDigito, strNombreCompleto, strApellidos, strRazonSocial, strNombreFantasia, strTelefono, strCelular, intFechaNacimiento, strSexo, intIdRubro, strFlagDireccion];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        NSLog(@"Exito");
        
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        
        //****Id del cliente relacionado al usuario para grabar la sucursal por defecto con los datos de dirección

        NSLog(@"intIdClienteiPhone =%@", [[json objectAtIndex:0] objectForKey:@"usrid"]);
        
        //intIdClienteiPhone = [ [[json objectAtIndex:0] objectForKey:@"usrid"] intValue];
        
        //      [aiViewBtnFormiPhone stopAnimating];
        
        return YES;
    }else{
        
        NSLog(@"Error");
        
        //      [aiViewBtnFormiPhone stopAnimating];
        
        return NO;
    }
}

-(bool) updateSqlClient{

    bool blnRetorno = YES;

    blnRetorno = [self updateUserSystem];
    
    if (blnRetorno) {
        
        if ([self validarRegistro] == YES) {
            dao *objDAO = [[dao alloc] init];
            int intIdUsuario = [objDAO obtainCurrentIdUser];
            
            textRut.text = [textRut.text stringByReplacingOccurrencesOfString: @ "." withString: @ ""];
            
            NSArray *ArrayRut = [textRut.text componentsSeparatedByString: @"-"];
            
            int intRutCliente = [[ArrayRut objectAtIndex: 0] intValue];
            NSString *strDigito = [ArrayRut objectAtIndex: 1];
            
            NSString *strNombreCompleto = textNames.text;
            NSString *strApellidos = textLastName.text;
            NSString *strTelefono = textNumber.text;
            int intDia = [textDay.text intValue];
            int intMes = [textMonth.text intValue];
            int intAno = [textYear.text intValue];

            NSString *strDay = textDay.text;
            NSString *strMonth = textDay.text;
            
            if (strDay.length == 1) {
                strDay = [NSString stringWithFormat:@"0%@", strDay];
            }
            
            if (strMonth.length == 1) {
                strMonth = [NSString stringWithFormat:@"0%@", strMonth];
            }
            
            NSString *strFechaNacimiento = [NSString stringWithFormat:@"%@%@%@", textYear.text, strMonth, strDay];
            
            NSString *strSex = @"M";

            if (segmentedSexOption.selectedSegmentIndex == 0) {
                strSex = @"M"; //@"male";
            }else{
                strSex = @"F"; //@"female";
            }
            
            int intFormaPago = 0;
            
            int intRetorno = 0;

            NSString *strEmail = textEmail.text; //[objDAO obtainEmailUserSistem:intIdUsuario];
            
            strNombreCompleto = [strNombreCompleto stringByReplacingOccurrencesOfString: @ " " withString: @ "%20"];
            strApellidos = [strApellidos stringByReplacingOccurrencesOfString: @ " " withString: @ "%20"];
            
            bool blnRetornoCloud = [self insertClientCloud:intIdUsuario strEmail:strEmail intIdTipoCliente:1 intRutCliente:intRutCliente strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strRazonSocial:@"" strNombreFantasia:@"" strTelefono:@"" strCelular:strTelefono intFechaNacimiento:[strFechaNacimiento intValue] strSexo:strSex intIdRubro:-1 strFlagDireccion:@""];

            strNombreCompleto = [strNombreCompleto stringByReplacingOccurrencesOfString: @ "%20" withString: @ " "];
            strApellidos = [strApellidos stringByReplacingOccurrencesOfString: @ "%20" withString: @ " "];
            
            if ([objDAO obtainMaestroClientes: intIdUsuario] > 0) {
                
                if (blnRetornoCloud) {

                    //Actualizamos
                    intRetorno = [objDAO upateMaestroClientes:intRutCliente intIdUsuario:intIdUsuario strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strCodTelefono:@"" strTelefono:strTelefono intDia:intDia intMes:intMes intAno:intAno strSex:strSex intFormaPago:intFormaPago strEmail:strEmail];
                    
                    if (intRetorno < 0) {
                        blnRetorno = NO;
                        
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                        message:@"Error al actualizar los datos del cliente, intente nuevamente."
                                                                       delegate:nil
                                                              cancelButtonTitle:@"OK"
                                                              otherButtonTitles:nil];
                        [alert show];
                    }
                    
                }else{
                    
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:@"Error remoto al actualizar los datos del cliente, intente nuevamente."
                                                                   delegate:nil
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                    [alert show];
                }
                
                
            }else{
                
                if (blnRetornoCloud) {

                    intRetorno = [objDAO insertMaestroClientes:intRutCliente intIdUsuario:intIdUsuario strDigito:strDigito strNombreCompleto:strNombreCompleto strApellidos:strApellidos strCodTelefono:@"" strTelefono:strTelefono intDia:intDia intMes:intMes intAno:intAno strSex:strSex intFormaPago:intFormaPago strEmail:strEmail];
                    
                    if (intRetorno < 0) { //Creamos la dirección por estan en tablas separadas
                        blnRetorno = NO;
                        
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                        message:@"Error al grabar los datos del cliente, intente nuevamente."
                                                                       delegate:nil
                                                              cancelButtonTitle:@"OK"
                                                              otherButtonTitles:nil];
                        [alert show];
                    }
                    
                }else{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                    message:@"Error remoto al actualizar los datos del cliente, intente nuevamente."
                                                                   delegate:nil
                                                          cancelButtonTitle:@"OK"
                                                          otherButtonTitles:nil];
                    [alert show];
                
                
                }
                
                
            }
        }else{
            //Fallaron las validaciones de campos
            blnRetorno = NO;
        }
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:@"La constraseña actual no es correcta, intente nuevamente."
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }

    return blnRetorno;
}

- (void) updateAccountSelector:(NSTimer *) timer {
    
    [timerUpdatingAccount invalidate];
    timerUpdatingAccount = nil;
    
    /*
     1.- Lanzar un NSURL Session Task hacia el cloud sincrónico
     2.- Con respuesta grabar en sqlLite
     3.- Mandar mensaje de alerta
     */
    
    //Si todo lo anterior sucede bien ocultar la vista
    viewUpdating.hidden = YES;

    //Detenemos el timer
    bool blnRetorno = NO;
    
    blnRetorno = [self updateSqlClient];
    
    if (blnRetorno) {

        UIAlertView *alert;
        
        alert =[[UIAlertView alloc] initWithTitle:@"" message:@"Su información fue actualizada exitósamente" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        
        [alert show];
    }
    
//--------------------------------------------------------------------
    objBtnUpdateCancel.title = @"Editar";
    
    [self editValuesItems:NO];
    
    textEmail.placeholder = textEmail.text;
    textEmail.text = @"";
/*
    textActualPassword.placeholder = @"******"; //textActualPassword.text;
    textActualPassword.text = @"";
    
    textPassword.placeholder = @"******"; //textPassword.text;
    textPassword.text = @"";
    
    textRetypePassword.placeholder = @"******"; //textRetypePassword.text;
    textRetypePassword.text = @"";
*/
    textNames.placeholder = textNames.text;
    textNames.text = @"";
    
    textLastName.placeholder = textLastName.text;
    textLastName.text = @"";
    
    textRut.placeholder = textRut.text;
    textRut.text = @"";
    
    textNumber.placeholder = textNumber.text;
    textNumber.text = @"";
    
    textDay.placeholder = textDay.text;
    textDay.text = @"";
    
    textMonth.placeholder = textMonth.text;
    textMonth.text = @"";
    
    textYear.placeholder = textYear.text;
    textYear.text = @"";
    
    btnActualizar.hidden = YES;
    
//--------------------------------------------------------------------
}

- (IBAction)changeSexOption:(id)sender {
    
    switch (self.segmentedSexOption.selectedSegmentIndex) {
        case 0:{
            /* Hombre */
            
            /*Flurry Stack trace*/
            //--------------------------
            [Flurry setGender:@"M"];
            //--------------------------
            
            break;
        }
        case 1:{
            /* Mujer */
            
            /*Flurry Stack trace*/
            //--------------------------
            [Flurry setGender:@"F"];
            //--------------------------
            
            break;
        }
    }
    
}

- (void) editValuesItems:(BOOL)blnParam{

//  textEmail.userInteractionEnabled = blnParam;
    textActualPassword.userInteractionEnabled = blnParam;
    textPassword.userInteractionEnabled = blnParam;
    textRetypePassword.userInteractionEnabled = blnParam;
    
    textNames.userInteractionEnabled = blnParam;
    textLastName.userInteractionEnabled = blnParam;
    textRut.userInteractionEnabled = blnParam;
    textNumber.userInteractionEnabled = blnParam;
    textDay.userInteractionEnabled = blnParam;
    textMonth.userInteractionEnabled = blnParam;
    textYear.userInteractionEnabled = blnParam;

    segmentedSexOption.userInteractionEnabled = blnParam;
    
}
//---------------------------------------------------------------------

- (NSString *) obtenerRutaBD{
    NSString *dirDocs;
    NSArray *rutas;
    NSString *rutaBD;
    
    rutas = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    dirDocs = [rutas objectAtIndex:0];
    
    NSFileManager *fileMgr = [NSFileManager defaultManager];
    rutaBD = [[NSString alloc] initWithString:[dirDocs stringByAppendingPathComponent:@"ecommerce.sqlite"]];
    
    if([fileMgr fileExistsAtPath:rutaBD] == NO){
        [fileMgr copyItemAtPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"ecommerce.sqlite"] toPath:rutaBD error:NULL];
    }
    
    return rutaBD;
}

- (void) retrieveClient{
    
    dao *objDAO = [[dao alloc] init];
    int intIdUser;
    
    intIdUser = [objDAO obtainCurrentIdUser];
    
    //Obtiene los datos almacenados desde sql Lite
    //------------------------------------------------
    NSString *ubicacionDB = [self obtenerRutaBD];
    
    if(!(sqlite3_open([ubicacionDB UTF8String], &bd) == SQLITE_OK)){
        NSLog(@"Database connection failure irn");
    }
    
    NSString *sqlSelect = [NSString stringWithFormat:@"SELECT MC_RUT_CLIENTE, MC_DIGITO, MC_NOMBRE_COMPLETO, MC_APELLIDOS, MC_TELEFONO, MC_DIA, MC_MES, MC_ANO, MC_SEXO, MCLI_FORMA_PAGO FROM ECOM_MAESTRO_CLIENTES WHERE USIS_ID = %i", intIdUser];
    
    const char *sentenciaSQL = [sqlSelect UTF8String];
    
    sqlite3_stmt *sqlStatement;
    
    if(sqlite3_prepare_v2(bd, sentenciaSQL, -1, &sqlStatement, NULL) != SQLITE_OK){
        NSLog(@"Exception to prepare statement");
    }
    
    NSString *strRutCliente, *strIdComuna, *strDigito, *strNombreCompleto, *strApellidos, *strTelefono, *strDia, *strMes, *strAno, *strSexo, *strFormaPago;
    
    while(sqlite3_step(sqlStatement) == SQLITE_ROW){
        
        strRutCliente = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
        
        strDigito = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
        
        strNombreCompleto = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
        
        strApellidos = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,3 )];
        
        strTelefono = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,4 )];
        
        strDia = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,5 )];
        
        strMes = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,6 )];
        
        strAno = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,7 )];
        
        strSexo = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,8 )];
        
        strFormaPago = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,9 )];
        
    }
    
    NSLog(@"strRutCliente     =%@", strRutCliente);
    NSLog(@"strIdComuna       =%@", strIdComuna);
    NSLog(@"strDigito         =%@", strDigito);
    
    NSLog(@"strNombreCompleto =%@", strNombreCompleto);
    NSLog(@"strApellidos      =%@", strApellidos);
    NSLog(@"strTelefono       =%@", strTelefono);
    
    NSLog(@"strDia =%@", strDia);
    NSLog(@"strMes =%@", strMes);
    NSLog(@"strAno =%@", strAno);
    
    NSLog(@"strSexo=%@", strSexo);
    NSLog(@"strFormaPago=%@", strFormaPago);
    
    textNames.placeholder = strNombreCompleto;
    textLastName.placeholder = strApellidos;
    textNumber.placeholder = strTelefono;
    
    if ( ([strRutCliente  isEqual: @"0"]) || (strRutCliente == NULL) )  {
        
        strRutCliente = @"";
        strDigito = @"";
        
    }else {
        textRut.placeholder = [NSString stringWithFormat:@"%@-%@", strRutCliente, strDigito];
    }
    
    textDay.placeholder = strDia;
    textMonth.placeholder = strMes;
    textYear.placeholder = strAno;
}

-(void) retrieveUserSistemData{

    dao *objDAO = [[dao alloc] init];
    int intIdUser;
    
    intIdUser = [objDAO obtainCurrentIdUser];
    
    if (intIdUser == -1) {
        intIdUser = 1;
    }

    NSArray *ArrayUserData;
    
    ArrayUserData = [objDAO obtainDatosUserSistem:intIdUser];

    if (ArrayUserData.count > 0) {
        textEmail.placeholder = ArrayUserData[1];

        textActualPassword.text = ArrayUserData[2];
        textPassword.text = ArrayUserData[2];
        textRetypePassword.text = ArrayUserData[2];
    }
    
/*
    strIdUser = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,0 )];
    strEmail = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,1 )];
    strPassword = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
    strSocialLogin = [NSString stringWithUTF8String:(char *)sqlite3_column_text(sqlStatement,2 )];
*/

}

- (void)viewWillAppear:(BOOL)animated {
    
    blnNumerActiveAccount = NO;
    btnActualizar.hidden = YES;
    
    viewUpdating.hidden = YES;
    
    [self editValuesItems:NO];

    [self retrieveUserSistemData];
    
    [self retrieveClient];

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    textEmail.delegate = self;
    textActualPassword.delegate = self;
    textPassword.delegate = self;
    textRetypePassword.delegate = self;
    
    textNames.delegate = self;
    textLastName.delegate = self;
    textRut.delegate = self;
    textNumber.delegate = self;
    textDay.delegate = self;
    textMonth.delegate = self;
    textYear.delegate = self;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)backToHomeArea:(id)sender {
    
        [self.navigationController popToRootViewControllerAnimated:YES];
    
}

@end





